<template>
  <view class="my">
    <view class="login" v-if="!isLogin">
      <button open-type="getPhoneNumber" class="btnLogin" @getphonenumber="getPhoneNumber">本机号码一键登录</button>
      <u-checkbox v-model="checked" @change="onCheckChange">
        <view class="text">我已阅读并同意<text class="blue" @click="fLink">《用户协议》</text> 和
          <text class="blue" @click="fLink">《隐私条款》</text>
        </view>
      </u-checkbox>
    </view>
    
    <view class="userInfo" v-if="isLogin">
      <view class="avatar">
        <img :src="userData.avatar" />
      </view>
      <view v-if="userData.name" class="nickname">{{ userData.name }}</view>
      <!-- <u-icon name="setting" class="fr" color="#707070" size="45" @click="showFixUserInfoPop = true"></u-icon> -->
    </view>

    <view class="bind" v-if="isLogin">
      <text>{{ userCnt ? '已绑定' : '未绑定' }}</text>
      <text>
        <text class="blue">{{ userCnt }}</text>位老人
      </text>
    </view>
  </view>
</template>

<script>
import { login, getUserMe, userCnt } from "@/api"

export default {
  components: {
   
  },
  data() {
    return {
      isLogin: false,
      userData: {
        avatar: 'https://static.wemlink.com/images/icon_line.png',
        nickname: 'xxxx'
      },
      code: '',
      userCnt: 0,
      checked: false,
    };
  },
  onLoad() {
    
  },
  async onReachBottom() {
    if(!this.isLoadMore) {
      this.isLoadMore = true
    }
	},
  onPullDownRefresh() {
    uni.showLoading({
      title: '刷新中...',
    })
  },
  onShow() {
    this.isLogin = this.$storage.getStorage("token") || "";
    if (this.isLogin) {
      this.fGetUserInfo()
      this.fUserCnt()
    }
  },
  methods: {
    fUserCnt(){
      userCnt().then(res => {
        this.userCnt = res.data
      })
    },
    fGetUserInfo(){
      getUserMe().then(res => {
				if (res.code === 0) {
					this.userData = res.data
				}
			})
    },
    async loginFun(e) {
      let _this = this

      uni.login({
        success: res => {
          _this.code = res.code;
          _this.$storage.setStorage("openId", res.code);
          
          console.log('code', res.code)
          console.log('phoneCode', e.detail.code)

          login({
            code: res.code,
            phoneCode: e.detail.code,
            // phone
          }).then(res => {
            // 记录本次有过登录行为
            _this.$store.commit("SET_Login", true);
            let { token } = res.data;
            _this.$store.dispatch("setToken", { token: token });
            _this.$toastr.msg("登录成功");
            _this.isLogin = true
            
            console.log('res.data:', res.data)
            _this.$store.dispatch('setUser', {
              userInfo: {
                ...res.data
              }
            })
            _this.fGetUserInfo()
            _this.fUserCnt()
            
            setTimeout(() => {
              if (_this.$mp.query && _this.$mp.query.open_url) {
                _this.$router.open(decodeURIComponent(_this.$mp.query.open_url),{
                  open_type:'redirectTo'
                });
              } else {
                let navs = getCurrentPages();
                if (navs.length > 1) {
                  _this.$router.back();
                } else {
                  _this.$router.open("hyay://open/pages/my/index");
                }
              }
            }, 500);
          }).catch((res)=>{
            uni.showToast({
              title: res.msg,
              icon: 'none',
            });
          })
        },
        fail:err => {
          this.$toastr.msg(JSON.stringify(err));
        }
      });

      return 
      uni.request({
        url: 'https://api.weixin.qq.com/cgi-bin/stable_token',
        method: 'POST',
        data: {
          appid: 'wxf9b1b385451bd070',
          secret: '0c69a2c1d0341d858a0f773f43ca0c48',
          grant_type: 'client_credential'
        },
        success(res) {
          console.log('获取access_token信息：', res)
          _this.accessToken = res.data.access_token
          uni.request({
            url: `https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=${res.data.access_token}`,
            method: 'POST',
            data: {
              code: e.detail.code
            },
            success(res) {
              console.log('获取的用户手机号userPhone：', res.data.phone_info.phoneNumber)
              let phone = res.data.phone_info.phoneNumber
              
            }
          })
        }
      })
    },
    getPhoneNumber(e) {  // 登录
      console.log('this.checked: ', this.checked)
      if(!this.checked){
        return this.$toastr.msg("请阅读并勾选用户协议和隐私条款！");
      }
      if(e.detail.errMsg == "getPhoneNumber:ok"){
        let that = this;
        wx.checkSession({
          success() {
            that.loginFun(e);
          },
          fail(e) {
            console.log('that', that)
            console.log('e: ', e)
            // that.getCode();
            that.loginFun(e)
            that.$toastr.msg("解析失败，请重新登录");
          }
        });
      }else{
        this.$toastr.msg("拒绝授权将导致部分功能不可用");
      }
    },
    logout() {  // 退出登录
      this.$router.open("hyay://open/pages/index/index");
      this.$storage.setStorage("token", "");
      this.$store.dispatch("setUser", {
        userInfo: {}
      });
    },
    fLink(){
      wx.navigateTo({
        url: `/pages/home/index`
      });
    },
    onCheckChange(){

    }
  }
};
</script>

<style scoped lang="scss">
.my{
  width: 100%;
  height: 100%;
  background: linear-gradient(to bottom, #CFDAF7, #F7F7F7 26%);
}

.userInfo {
  text-align: center;
  padding-top: 30rpx;

  .avatar {
    width: 128rpx;
    height: 128rpx;
    border-radius: 64rpx;
    margin: 0 auto 10rpx auto;

    img {
      width: 128rpx;
      height: 128rpx;
      border-radius: 50%;
      background: #d1d1d1;
    }
  }
  .nickname{
    color: #000;
    font-size: 32rpx;
  }
}

.login{
  width: 100%;
  position: absolute;
  left: 50%;
  top: 50%;
  padding: 0 60rpx;
  text-align: center;
  transform: translate(-50%, -70%);

  .btnLogin{
    color: #fff;
    font-size: 30rpx;
    background-color: #2761FF;
    border-radius: 54rpx;
    margin-bottom: 60rpx;
  }

  .text{
    color: #A4A4AB;
    font-size: 26rpx;
  }
}

.bind{
  display: flex;
  padding: 38rpx 30rpx;
  margin: 80rpx 25rpx;
  border-radius: 16rpx;
  background: #fff;
  justify-content: space-between;

  text{
    color: #363434;
    font-size: 28rpx;
  }
  .blue{
    color: #2761FF;
  }
}
</style>